<?php
/**
 * Copyright (c) 2018-2019.
 *  This file is part of the moonpie production
 *  (c) johnzhang <875010341@qq.com>
 *  This source file is subject to the MIT license that is bundled
 *  with this source code in the file LICENSE.
 */

/**
 * Created by PhpStorm.
 * User: johnzhang
 * Date: 2019/7/29 0029
 * Time: 上午 9:27
 */

namespace moonpie\plugin\wechat_account\model;


use app\common\model\BaseModel;
use EasyWeChat\Kernel\Support\Arr;
use moonpie\plugin\wechat_account\service\WechatAccountServiceConfig;
use think\Cache;

class WechatAccount extends BaseModel
{
    const ACCOUNT_TYPE_PERSON = 1;
    const ACCOUNT_TYPE_PERSON_AUDIT = 2;
    const ACCOUNT_TYPE_OFFICIAL = 4;
    const ACCOUNT_TYPE_OFFICIAL_AUDIT = 8;
    const ACCOUNT_TYPE_WORK = 16;
    const STATUS_VALID = 1;
    const STATUS_DROPPED = -1;
    const TMPL_RECORD_LOAD_CACHE_KEY = 'wechat_account:config-cache:%s';
    protected $service;
   protected $serviceConfig;
    protected function initialize()
    {
        parent::initialize();
        static::afterWrite(function($record){
            $cache_key = sprintf(static::TMPL_RECORD_LOAD_CACHE_KEY,  $record['id']);
            Cache::rm($cache_key);
            $cache_key = sprintf(static::TMPL_RECORD_LOAD_CACHE_KEY,  $record['app_id']);
            Cache::rm($cache_key);
        });
    }

    /**
     * 获取公众号服务接口
     * @return \EasyWeChat\OfficialAccount\Application
     */
    public function getService()
    {
        if(is_null($this->service)) {
            $config = $this->buildServiceConfig();
            $this->service = call_user_func("\\Moonpie\\Macro\\Factory::{$config['service']}", $config['config']);
            //这里设置缓存服务
            if($this->service) {
                $cache_service = $this->getServiceConfig()->getCachingService();
                if(!is_null($cache_service)) $this->service->rebind('cache', $cache_service);
            }
            return $this->service;
        }
        return $this->service;
    }
    protected function buildServiceConfig()
    {
        $config = [
            'app_id' => $this->getData('app_id'),
            'secret' => $this->getData('secret'),
            'token' => $this->getData('token'),
            'aes_key' => $this->getData('encrypt_key'),
        ];
        //现在处理日志部分
        $config['log'] = $this->getServiceConfig()->getLoggingConfig();
        switch ($this->getData('type')){
            case self::ACCOUNT_TYPE_WORK:
                $service = 'work';
                break;
            default:
                $service = 'officialAccount';
                break;
        }
        return compact('service', 'config');

    }
    public static function getValidTypes()
    {
        return [
            static::ACCOUNT_TYPE_PERSON => '订阅号',
            static::ACCOUNT_TYPE_PERSON_AUDIT => '认证订阅号',
            static::ACCOUNT_TYPE_OFFICIAL => '服务号',
            static::ACCOUNT_TYPE_OFFICIAL_AUDIT => '认证服务号',
            static::ACCOUNT_TYPE_WORK => '企业号',
        ];
    }
    public function getTypeAttr($attr)
    {
        $types = static::getValidTypes();
        return Arr::get($types, $attr, '未知类型');
    }
    public function markAsDropped()
    {
        return false !== $this->save(['status' => static::STATUS_DROPPED]);
    }
    public static function loadByAppid($appid)
    {
        $cache_key = sprintf(static::TMPL_RECORD_LOAD_CACHE_KEY,  $appid);
        $record = static::where('app_id', $appid)->cache($cache_key)->find();
        if(!$record) return false;
        if($record->getData('status') !== static::STATUS_VALID) return null;
        return $record;
    }
    public static function loadById($id)
    {
        $cache_key = sprintf(static::TMPL_RECORD_LOAD_CACHE_KEY,  $id);
        $record = static::where('id', $id)->cache($cache_key)->find();
        if(!$record) return false;
        if($record->getData('status') !== static::STATUS_VALID) return null;
        return $record;
    }
    public function getAppId()
    {
        return $this->getData('app_id');
    }
    public function getServiceConfig()
    {
        if(is_null($this->serviceConfig)){
            $this->serviceConfig = new WechatAccountServiceConfig($this);
        }
        return $this->serviceConfig;
    }
}